import React from 'react';
import { RestLink } from 'apollo-link-rest';
import 'antd/dist/antd.min.css';
import fetch from 'API/fetch';
import ReactDOM from 'react-dom'
import App from './App'
import TaskReport from './reports/task_report';
import { name, version } from '../../package.json';
import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client'
import { setContext } from '@apollo/client/link/context';


import { AVILIABLE_TASK_MAP, JOB_TASK_TYPES } from '../common/constants';
import './style.css';

if (!sessionStorage.resD) {
	sessionStorage.setItem('resD', JSON.stringify({ feature: {}, balance: {} }));
}
export const getResD = async () => {
	const resD = await fetch('/api/v2/users/balance/get', {
		method: 'GET',
	});
	if (resD.code === 200) {
		sessionStorage.setItem('resD', JSON.stringify(resD.results));
	}
};
export default (kuiper /* , options */) => {
	Object.assign(
		(kuiper.app.apolloInMemoryCache.typePolicies =
			kuiper.app.apolloInMemoryCache.typePolicies || {}),
		{
			TaskResult: { merge: true },
			TaskResultWarnings: { keyFields: ['_id'] },
			ExplictKeywordCategory: { keyFields: ['type'] },
			Job: {
				fields: JOB_TASK_TYPES.reduce(
					(obj, type) => {
						if (AVILIABLE_TASK_MAP[type]) {
							obj[`${type}Settings`] = {
								merge(existing, incoming) {
									if (!existing || !(existing || []).filter(Boolean).length) {
										return incoming;
									}

									const existMap = (existing || []).reduce((obj, x) => {
										obj[x.target] = x;
										return obj;
									}, {});
									return Object.values(
										(incoming || []).reduce((obj, x) => {
											if (x.target in existMap) {
												obj[x.target] = { ...existMap[x.target], ...x };
											} else {
												obj[x.target] = x;
											}
											return obj;
										}, {})
									);
								},
							};
						} else {
							obj[`${type}Settings`] = {
								merge(existing, incoming) {
									return { ...existing, ...incoming };
								},
							};
						}
						return obj;
					},
					{
						target: {
							merge(existing, incoming) {
								return { ...existing, ...incoming };
							},
						},
					}
				),
			},
			Balance: {
				fields: {
					balance: {
						merge(existing = {}, incoming = {}) {
							return { ...existing, ...incoming };
						},
					},
				},
			},
		}
	);
	kuiper.app.apolloLinks.push(
		new RestLink({
			endpoints: {
				v1: '/api/v1',
				v2: '/api/v2',
			},
		})
	);
	kuiper.app.palette = [
		'#409EFF',
		'#FF8D85',
		'#FFAB67',
		'#4FD7A1',
		'#6DC8EC',
		'#BDD2FD',
		'#FFC5B8',
		'#FDEFBD',
		'#8BADF5',
		'#BDEFDB',
		'#B0E8F4',
		'#DAABF2',
		'#F2ABD0',
	];
	kuiper.app.apollo = new ApolloClient({
		defaultOptions: {
			query: {
				fetchPolicy: 'cache-and-network',
				nextFetchPolicy: 'cache-first',
			},
		},
		link: from([
			setContext((_, { headers }) => {
				const search = new URLSearchParams(location.search);
				const token = search.get('token');

				if (!token) return {};

				return {
					headers: {
						...headers,
						Authorization: `Bearer ${token}`,
					},
				};
			}),
			from([...kuiper.app.apolloLinks,
				new HttpLink({
					uri: '/graphql',
					credentials: 'same-origin',
				}),
			])
		]),
		cache: new InMemoryCache(kuiper.app.apolloInMemoryCache),
	});
	// 应用主题的 CSS 变量
	Object.entries(kuiper.app.config['@kuiper/react-base'].theme).forEach(([key, value]) => {
		document.documentElement.style.setProperty(key, value);
	});
	return {
		name,
		version,
		dependencies: ['@kuiper/graphql'],
		register() {
		const isReport  = window.location.hash.indexOf('report/task_report') > -1
			return ReactDOM.render(
				<React.StrictMode>
					{isReport ? <TaskReport /> : <App />}
				</React.StrictMode>,
				document.getElementById('kuiper_app')
			)
		},
	};
};
